package com.mercenary.wein.screenControl.ui;

import com.mercenary.wein.screenControl.bean.GroupMetaBean;
import com.mercenary.wein.screenControl.service.GroupService;
import com.mercenary.wein.screenControl.ui.inter.GroupComboBoxOb;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by tuxiao on 2017/3/18.
 */
public class GroupComboBox extends JComboBox {
    private List<GroupMetaBean> combos = new ArrayList<GroupMetaBean>();
    static GroupService groupService = new GroupService();
    private long selectedGid;

    public long getSelectedGid() {
        return selectedGid;
    }

    GroupComboBoxOb observer;

    public void registerObserver(GroupComboBoxOb observer){
        this.observer = observer;
    }

    public void notifyGroupChange(long gid){
        this.observer.refreshData(gid);
    }

    public GroupComboBox(){
        combos.add(new GroupMetaBean(0,"全部手机",""));
        selectedGid=0;

        List<GroupMetaBean> gmbs = groupService.getAllGroupMetaBean();
        for(GroupMetaBean gmb : gmbs){
            combos.add(gmb);
        }

        refreshData();
        this.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int index = GroupComboBox.this.getSelectedIndex();
                selectedGid = combos.get(index).getGcode();
                notifyGroupChange(selectedGid);
            }
        });
    }

    public void refreshData(){
        this.removeAllItems();
        for(GroupMetaBean s:combos){
            this.addItem(s.getGname());
        }
        int index = getSelectedIndex();
        selectedGid = combos.get(index).getGcode();
    }

    public void addItem(GroupMetaBean gmb){
        combos.add(gmb);
        this.addItem(gmb.getGname());
    }
}
